import React, { useState, useRef, useEffect } from 'react';
import { PlusOutlined, EditOutlined, DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { ProTable, ActionType, ProColumns, PageContainer } from '@ant-design/pro-components';
import { Button, Modal, Form, Input, message, Tree, Switch, TreeSelect } from 'antd';
import { createSysDept,updateSysDept, deleteSysDept, fetchSysDept, updateDeptStatus ,queryDeptTree} from '@/services/ant-design-pro/system';
import { useModel } from '@umijs/max';

interface Department {
  id: string;
  name: string;
  parentCode?: string;
  children?: Department[];
  status?: boolean;
  address?: string;
  code?: string;
  createId?: string;
  createTime?: string;
  deptAllName?: string;
  deptCode?: string;
  deptIsleaf?: number;
  deptLevel?: number;
  deptManager?: string;
  deptName?: string;
  deptPath?: string;
  deptRemark?: string;
  deptType?: number;
  detailAddress?: string;
}

const DepartmentManagement: React.FC = () => {
  const { refreshData } = useModel('roleModel');
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [visible, setVisible] = useState(false);
  const [currentDepartment, setCurrentDepartment] = useState<Department | null>(null);
  const [treeData, setTreeData] = useState<Department[]>([]);
  const [messageApi, contextHolder] = message.useMessage();
  
  useEffect(() => {
    // 初始化 treeData
    const initTreeData = async () => {
      try {
        const response = await queryDeptTree({});
        if (response && response.data) {
          setTreeData(response.data);
        }
      } catch (error) {
        message.error('加载部门数据失败');
      }
    };

    initTreeData();
  }, []);
  
  const handleAdd = () => {
    setCurrentDepartment(null);
    form.resetFields();
    setVisible(true);
  };

  const handleAddChild = (parent: Department) => {
    console.log(parent,'parent')
    setCurrentDepartment({ ...parent, id: '', name: '', parentCode: parent.code ,deptName:''});
    form.resetFields();
    form.setFieldsValue({ parentCode: parent.code ,deptName:''});
    setVisible(true);
  };

  const handleEdit = (record: Department) => {
    const obj:any = {};
    obj.deptName = record.name
    obj.parentCode = record.parentCode
    console.log(record,'record')
    setCurrentDepartment({ ...record, ...obj });
    form.setFieldsValue({ ...record, ...obj });
    setVisible(true);
  };

  const handleDelete = async (id: string) => {
    console.log(id,'id')
    try {
      await deleteSysDept(id);
      message.success('删除成功');
      refreshData()
      actionRef.current?.reload();
      
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: Department) => {
    try {
      if (currentDepartment && currentDepartment.id) {
        await updateSysDept({ ...currentDepartment, ...values });
        message.success('更新成功');
      } else {
        console.log(values,'values')
        if(values.parentCode){
            await createSysDept(values);
            message.success('添加成功');
        }
       
      }
      setVisible(false);
      actionRef.current?.reload();
      refreshData()
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleStatusChange = async (prOnOff: boolean, id: string) => {
    try {
      await updateDeptStatus( {id, prOnOff: prOnOff ? '1' : '0 '});
      message.success('状态更新成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  const columns: ProColumns<Department>[] = [
    {
      title: '部门名称',
      dataIndex: 'name',
      key: 'name',
    },
    // {
    //   title: '部门全称',
    //   dataIndex: 'deptAllName',
    // },
    //    {
    //   title: '部门全称',
    //   dataIndex: 'deptAllName',
    // },
    // {
    //   title: '状态',
    //   dataIndex: 'prOnOff',
    //   render: (text, record) => (
    //     <Switch
    //     checked={record.prOnOff === '1'}
    //       onChange={(checked) => handleStatusChange(checked, record.id)}
    //     />
    //   ),
    // },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record) => [
        <a key="add-child" onClick={() => handleAddChild(record)}>
          <PlusCircleOutlined /> 添加子级
        </a>,
        <a key="edit" onClick={() => handleEdit(record)}>
          <EditOutlined /> 编辑
        </a>,
        <a key="delete" onClick={() => handleDelete(record.id)}>
          <DeleteOutlined /> 删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer header={{title:''}}>
         {contextHolder}
      <ProTable<Department> 
        actionRef={actionRef}
        // childrenColumnName={'treeList'}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          // <Button type="primary" key="add" onClick={handleAdd}>
          //   <PlusOutlined /> 添加
          // </Button>,
        ]}
        request={(params) => fetchSysDept({ params})}
        columns={columns}
        expandable={{
          defaultExpandAllRows: true,
          childrenColumnName:'treeList'
        }}
      />
      <Modal
        title={currentDepartment ? '编辑部门' : '添加部门'}
        open={visible}
        onCancel={() => setVisible(false)}
        onOk={form.submit}
      >
        <Form form={form} onFinish={handleSubmit}>
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>
          {currentDepartment?.parentCode !== '0' && <Form.Item name="parentCode" label="选择父级部门" rules={[{ required: true, message: '请选择父级部门' }]}>
            <TreeSelect
              treeData={treeData}
              fieldNames={{ label: 'name', value: 'code', children: 'treeList' }}
              
              onSelect={(selectedKeys) => form.setFieldsValue({ parentCode: selectedKeys })}
            />
          </Form.Item>}
          
          <Form.Item name="deptName" label="部门名称" rules={[{ required: true, message: '请输入部门名称' }]}>
            <Input />
          </Form.Item>
          {/* <Form.Item name="address" label="地址">
            <Input />
          </Form.Item> */}
          {/* <Form.Item name="deptAllName" label="部门全称">
            <Input />
          </Form.Item>
          <Form.Item name="deptManager" label="部门负责人">
            <Input />
          </Form.Item> */}
        </Form>
      </Modal>
      </PageContainer>
  );
};

export default DepartmentManagement;
